#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QColorDialog>
#include "qgraphicdialog.h"
#include <QTextStream>
#include <QStyle>
#include <QRegExp>
#include <QFileDialog>
#include <QErrorMessage>
#include <QtSvg/QSvgGenerator>
#include <QPainter>
#include "qpaintutils.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    renderArea = new QRenderArea;

    connect(ui->actionSave_as, &QAction::triggered, this, &MainWindow::onSaveAs);

    mainLayout = new QGridLayout;
    mainLayout->addWidget(renderArea);

    ui->centralWidget->setLayout(mainLayout);

    setWindowTitle("Maksymenko laba3");
}

MainWindow::~MainWindow()
{
    delete mainLayout;
    delete renderArea;
    delete ui;
}

void MainWindow::on_actionMy_dialog_triggered()
{
    QGraphicDialog dialog(this);
    connect(&dialog, &QGraphicDialog::closed, this, &MainWindow::onDialogClosed);
    dialog.exec();
}

void MainWindow::onDialogClosed(QColor *color, QString text, int diameter)
{
    mainLayout->setColumnMinimumWidth(0, diameter + 10);
    mainLayout->setRowMinimumHeight(0, diameter + 10);

    renderArea->setVisible(true);
    renderArea->setDiameter(diameter);
    renderArea->setColor(color);
    renderArea->setText(text);
    renderArea->draw(true);
}

void MainWindow::onSaveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save html file and image", QDir::homePath(), "HTML file *.html (*.html)");

    if(!fileName.isEmpty())
    {
        QFile::copy(QFile(":/html/index.html").fileName(), fileName);
        QFileInfo fileInfo(fileName);

        QFile imgFile(fileInfo.path() + QDir::separator() + "result.svg");

        if(!imgFile.open(QIODevice::WriteOnly))
        {
            QErrorMessage msg;
            msg.showMessage("Unable to create .svg file");
        }
        else
        {
            QSvgGenerator generator;
            generator.setSize(this->renderArea->size());
            generator.setOutputDevice(&imgFile);
            QPainter painter;
            painter.begin(&generator);

            QPoint center(width() / 2, height() /2);

            QPaintUtils::drawCircle(&painter, &center, renderArea->getDiameter(), renderArea->getText(), 20, renderArea->getColor());

            painter.end();
            imgFile.close();
        }
    }

}

void MainWindow::on_actionClose_triggered()
{
    close();
}
